<template>
  <div class="login">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="登录" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script  lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import axios from "axios";
import {useRouter} from 'vue-router'
const router = useRouter()
interface RuleForm {
  username: string;
  password: string;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>(); 
const ruleForm = reactive<RuleForm>({
  username: "",
  password: "",
});

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],

  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("/api/login", ruleFormRef).then((res) => {
        console.log(res);
        if (res.data.code === 10000) {
          //存储token和用户信息
          localStorage.setItem("token", res.data.data.accessToken);
          localStorage.setItem(
            "userInfo",
            JSON.stringify(res.data.data.userInfo)
          );

          //成功信息提示
          ElMessage({
            message: "登录成功",
            type: "success",
          });
          //跳转到列表页面
          router.push('/')
        }else{
             ElMessage.error('登录失败')
        }
      });
    } 
  });
};
</script>

<style  scoped>
.login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>